<template>
  <div class="inputBasicContain">
    <!-- el-form ： label-width="120rpx"  
      修改前为: label-width="auto"
    -->
    <el-form
      ref="editFormRef"
      label-width="auto" 
      size="mini"
      :inline="true"
      :model="formParam"
      :disabled="
      basic == 'basic'
        ? showState != 0 && showState != 4
        : (showState != 0 && showState != 4) || rowIndex == null
    "
    >
      <template v-for="(item, index) in formParam.params">
        <el-form-item
          v-if="item.type != 'null'"
          :key="item.paramName"
          :prop="'params.' + index + '.value'"
          :rules="editRules[item.paramName]"
          class="inputNull"
        >
          <span slot="label">
            <span
              v-if="item.lockValue != null && item.openUrl != null &&item.value !=null && item.paramName !='isRectifyStep'"
              v-on:dblclick="rowDblclick(item)"
              style="color:blue"
            >{{item.title}}</span>
            <span
              v-if="(item.lockValue == null || item.openUrl == null ||item.value ==null) && item.type != 'button' && item.paramName !='isRectifyStep'"
            >{{item.title}}</span>
          </span>
          <!-- 文本 text -->
          <el-input
            v-if="item.type == 'text'"
            v-model="item.value"
            type="text"
            :style="{'border':  item.null ? '':'1px red solid'}"
            :disabled="!item.allow || showState == 4"
            :maxLength="item.maxLength"
          ></el-input>

          <!-- image -->
          <template v-else-if="item.type == 'image'">
            <div style="text-align:center;color:blue">
              <el-button
              type="primary"
                v-if="item.value"
                @click="openImage(item)"
              >查看</el-button>
              <el-button
              type="primary"
                v-else-if="!item.value"
                @click="putImage(item)"
              >上传</el-button>
            </div>
          </template>

          <!-- 文本 textColor -->
          <el-input
            class="textColor"
            v-if="item.type == 'textColor'"
            v-model="item.value"
            type="text"
            :style="{'border':  item.null ? '':'1px red solid'}"
            :disabled="!item.allow || showState == 4"
            :maxLength="item.maxLength"
          ></el-input>

          <!-- 整数 int -->
          <el-input
            v-else-if="item.type == 'int'"
            v-model="item.value"
            type="number"
            :disabled="!item.allow || showState == 4"
            min="0"
            :maxLength="item.maxLength"
            :style="{'border':  item.null ? '':'1px red solid'}"
          ></el-input>

          <!-- 小数 float -->
          <el-input
            v-else-if="item.type == 'float'"
            v-model="item.value"
            type="number"
            :disabled="!item.allow || showState == 4"
            :maxLength="item.maxLength"
            :style="{'border':  item.null ? '':'1px red solid'}"
          ></el-input>

          <!-- 密码 password -->
          <el-input
            v-else-if="item.type == 'password'"
            v-model="item.value"
            type="password"
            :disabled="!item.allow || showState == 4"
            :maxLength="item.maxLength"
            :style="{'border':  item.null ? '':'1px red solid'}"
          ></el-input>

          <!-- 地图显示 map -->
          <template v-else-if="item.type == 'map'">            
            <t-map :paramId="item.paramName" :val="item.value" ></t-map>
          </template>

          <!-- 时间选择 time -->
          <template v-else-if="item.type == 'time'">            
            <!-- <time-pick v-model="item.value" :value="item.value" ></time-pick> -->
            <el-time-select
              v-model="item.value"
              :picker-options="{
                start: '00:00',
                step: '00:05',
                end: '23:55'
              }"
              placeholder="选择时间">
            </el-time-select>
          </template>

          <!-- 小弹窗 dataSelect -->
          <template v-else-if="item.type == 'dataSelect'">
            <!-- 多选（弹窗形式（只能通过弹窗带出）） -->
            <template v-if="item.operateType == 'selectMany' || item.quickUrl == null">
              <el-input
                class="tableinput"
                v-model="item.value"
                :disabled="true"
                :style="{'border':  item.null ? '':'1px red solid'}"
              >
                <i
                  slot="suffix"
                  class="el-icon-search"
                  style="color: #30a7d6; font-weight: 700; font-size: 14px"
                  @click="openDialog(item)"
                  v-show="
                    basic == 'basic'
                      ? showState == 0 && item.allow
                      : rowIndex != null && showState == 0
                  "
                ></i>
              </el-input>
            </template>
            <!-- 单选（弹窗+下拉单选） -->
            <template v-else>
              <el-select
                v-model="item.value"
                filterable
                remote
                :remote-method="remoteMethod"
                :loading="loading"
                @focus="focusInput(item)"
                @visible-change="visibleChange"
                @change="returnData"
                value-key="name"
                :disabled="!item.allow || showState == 4"
                :style="{'border':  item.null ? '':'1px red solid'}"
              >
                <!-- 下拉的表头 -->
                <div class="headerTr">
                  <template v-for="item in selectHeader">
                    <div
                      v-if="item.type != 'null'"
                      class="selectHeaderClass"
                      :key="item.tableValue"
                    >{{ item.title }}</div>
                  </template>
                </div>
                <!-- 下拉的内容 -->
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.code"
                  :value="item"
                  class="optionContain"
                >
                  <div class="selectTr">
                    <template v-for="item1 in selectHeader">
                      <div
                        class="selectTd"
                        v-if="item1.type != 'null'"
                        :key="item1.tableValue"
                      >{{ item[item1.tableValue] }}</div>
                    </template>
                  </div>
                </el-option>
              </el-select>
              <span
                class="el-icon-search searchIcon"
                @click="openDialog(item)"
                v-if="showState == 0"
              ></span>
              <span
                class="el-icon-search searchIcon"
                v-if="item.lockValue != null && item.openUrl != null && showState != 0"
              ></span>
            </template>
          </template>

          <!-- 下拉选择器 baseSelect -->
          <template v-else-if="item.type == 'baseSelect'">
            <el-select
              v-model="item.value"
              :disabled="!item.allow || showState == 4"
              :style="{'border':  item.null ? '':'1px red solid'}"
              style="width:150px"
            >
              <el-option
                :label="item1.title"
                :value="item1.value"
                v-for="item1 in item.selectItems"
                :key="item1.title"
              ></el-option>
            </el-select>
            <span
              class="el-icon-circle-plus-outline searchIcon"
              @click="openDialog(item)"
              v-if="showState == 0"
            ></span>
            <span
              class="el-icon-circle-plus-outline searchIcon"
              v-if="item.lockValue != null && item.openUrl != null && showState != 0"
            ></span>
          </template>

          <!-- 下拉选择器 checkBox -->
          <template v-else-if="item.type == 'checkBox'">
            <div style="width:360px;height:auto; ">
              <el-checkbox
                v-for="item1 in item.selectItems"
                v-model="item1.selected"
                :label="item1.title"
                :key="item1.value"
                style="width:150px;"
              >{{item1.title}}</el-checkbox>
            </div>
          </template>

          <!-- 带出的数据填充框 dataSelectSub -->
          <el-input
            v-else-if="item.type == 'dataSelectSub'"
            v-model="item.value"
            type="text"
            disabled
            :style="{'border':  item.null ? '':'1px red solid'}"
          ></el-input>

          <!-- 文本 findSelectSub -->
          <el-input
            v-if="item.type == 'findSelectSub'"
            v-model="item.value"
            type="text"
            :style="{'border':  item.null ? '':'1px red solid'}"
            :disabled="!item.allow || showState == 4"
            :maxLength="item.maxLength"
          ></el-input>

          <!-- BOM版本 findSelect -->
          <el-select
            v-else-if="item.type == 'findSelect'"
            v-model="item.value"
            @focus="findSelectClick(item)"
            @visible-change="prepare($event, item)"
            value-key="name"
            :disabled="!item.allow || showState == 4"
            :style="{'border':  item.null ? '':'1px red solid'}"
          >
            <div class="headerTr">
              <template v-for="itemH in findSelectHeader">
                <div
                  v-if="itemH.type != 'null'"
                  class="selectHeaderClass"
                  :key="itemH.tableValue"
                >{{ itemH.title }}</div>
              </template>
            </div>
            <!-- 下拉的内容 -->
            <el-option
              v-for="itemOp in item.selectItems"
              :key="itemOp.id"
              :label="itemOp.version"
              :value="itemOp.id"
              class="optionContain"
              @click.native="findReturnData(itemOp)"
            >
              <div class="selectTr">
                <template v-for="item1 in findSelectHeader">
                  <div
                    class="selectTd"
                    v-if="item1.type != 'null'"
                    :key="item1.tableValue"
                  >{{ itemOp[item1.tableValue] }}</div>
                </template>
              </div>
            </el-option>
          </el-select>

          <!-- getSelect -->
          <el-select
            v-else-if="item.type == 'getSelect'"
            v-model="item.value"
            @focus="getSelectClick(item)"
            @visible-change="getPrepare($event, item)"
            value-key="name"
            :disabled="!item.allow || showState == 4"
            :style="{'border':  item.null ? '':'1px red solid'}"
          >
            <div class="headerTr">
              <template v-for="itemH in getSelectHeader">
                <div
                  v-if="itemH.type != 'null'"
                  class="selectHeaderClass"
                  :key="itemH.tableValue"
                >{{ itemH.title }}</div>
              </template>
            </div>
            <!-- 下拉的内容 -->
            <el-option
              v-for="itemOp in item.selectItems"
              :key="itemOp.id"
              :label="itemOp[item.paramName]"
              :value="itemOp[item.paramName]"
              class="optionContain"
              @click.native="getReturnData(itemOp)"
            >
              <div class="selectTr">
                <template v-for="item1 in getSelectHeader">
                  <div
                    class="selectTd"
                    v-if="item1.type != 'null'"
                    :key="item1.tableValue"
                  >{{ itemOp[item1.tableValue] }}</div>
                </template>
              </div>
            </el-option>
          </el-select>

          <!-- 单选按钮 radio (后端给的数据又string型和number型，分开判断) -->
          <template v-else-if="item.type == 'radio' && item.paramName !='isRectifyStep'">
            <template v-if="item.operateType == 'allowAny'">
              <el-checkbox
                v-if="typeof item.value == 'number'"
                v-model="item.value"
                :true-label="1"
                :false-label="0"
              ></el-checkbox>
              <el-checkbox v-else v-model="item.value" true-label="1" false-label="0"></el-checkbox>
            </template>
            <template v-else>
              <el-checkbox
                v-if="typeof item.value == 'number'"
                v-model="item.value"
                :true-label="1"
                :false-label="0"
                :disabled="!item.allow || showState == 4"
              ></el-checkbox>
              <el-checkbox
                v-else
                v-model="item.value"
                true-label="1"
                false-label="0"
                :disabled="!item.allow || showState == 4"
              ></el-checkbox>
            </template>
          </template>

          <!-- 下拉选择器 select -->
          <el-select
            v-else-if="item.type == 'select'"
            v-model="item.value"
            :disabled="!item.allow || showState == 4"
            :style="{'border':  item.null ? '':'1px red solid'}"
          >
            <el-option
              :label="item1.title"
              :value="item1.value"
              v-for="item1 in item.selectItems"
              :key="item1.title"
            ></el-option>
          </el-select>

          <!-- null型 -->
          <el-input
            class="inputNull"
            v-else-if="item.type == 'null'"
            v-model="item.value"
            disabled
            :style="{'border':  item.null ? '':'1px red solid'}"
          ></el-input>

          <!-- 日期型 dataTime -->
          <el-date-picker
            v-model="item.value"
            type="date"
            :placeholder="item.allow ? '选择日期' : ''"
            v-else-if="item.type == 'dateTime'"
            :disabled="!item.allow || showState == 4"
            :style="{'border':  item.null ? '':'1px red solid'}"
            value-format="yyyy-MM-dd"
          ></el-date-picker>

          <!-- 日期范围型 dateTimeFrame -->
          <el-date-picker
            v-else-if="item.type == 'dateTimeFrame'"
            v-model="item.value"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="-"
            :disabled="!item.allow || showState == 4"
            :style="{'border':  item.null ? '':'1px red solid','width':'200px'}"
            start-placeholder="开始"
            end-placeholder="结束"
          ></el-date-picker>

          <!-- 月份范围型 dateTimeFrame2 -->
          <el-date-picker
            v-else-if="item.type == 'dateTimeFrame2'"
            v-model="item.value"
            type="monthrange"
            :disabled="!item.allow || showState == 4"
            :style="{'border':  item.null ? '':'1px red solid','width':'200px'}"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份">
          </el-date-picker>

          <!-- 年份月份选择 yearMonth -->
          <el-date-picker
            v-else-if="item.type == 'yearMonth'"
            v-model="item.value"
            type="month"
            format="yyyy-MM" value-format="yyyy-MM"
            :style="{'border':  item.null ? '':'1px red solid','width':'150px'}"
            >
          </el-date-picker>

          <!-- 日期型 dataTime2 -->
          <el-input
            v-model="item.value"
            type="text"
            :placeholder="item.allow ? '选择日期' : ''"
            v-else-if="item.type == 'dateTime2'"
            :disabled="!item.allow || showState == 4"
            :style="{'border': item.null ? '':'1px red solid'}"
          ></el-input>

          <!-- 日期型 dataTime3 -->
          <el-date-picker
            v-else-if="item.type == 'dateTime3'"
            v-model="item.value"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm"
            :placeholder="item.allow ? '选择日期时间' : ''"
            :disabled="!item.allow || showState == 4"
          ></el-date-picker>

          <!-- 文本框 textarea -->
          <el-input
            v-model="item.value"
            type="textarea"
            v-else-if="item.type == 'textarea'"
            :disabled="!item.allow || showState == 4"
            class="inputBasicTextArea"
            :style="{'border': item.null ? '':'1px red solid'}"
          ></el-input>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { async } from 'q';
import TMap from "./map.vue";
import { TimePick } from 'element-ui'

export default {
  name:"编辑工具组件",
  components:{
    TMap,
    TimePick
  },
  data() {
    return {
      a: 12,
      quickUrl: "",
      orgData: null,
      isAllow: 0,

      loading: false,
      selectHeader: [],
      options: [],
      findSelectHeader: [],
      findOptions: [],
      findPreData: {}, // 下拉select的时候，存储原来的值

      getSelectHeader: "",
      getOptions: [],
      getPreData: {},
      materialId: "" // 工艺路线物料选中 findSelect
    };
  },
  props: {
    formParam: {
      type: Object,
      default: () => {
        return {};
      }
    },
    showState: {
      type: Number,
      default: () => {
        return 0;
      }
    },
    editRules: {
      type: Object,
      default: () => {
        return {};
      }
    },
    basic: {
      type: String,
      default: ""
    },
    model: {
      type: Number,
      default: null
    },
    rowIndex: {
      //选择的行
      type: Number,
      default: null
    }
  },
  created() {
    this.orgData = JSON.parse(sessionStorage.getItem("orgData"));
  },
  mounted() {},
  watch: {
    // 对明细部分的【表单监听】，是否有选择明细部分的行数据
    rowIndex: {
      handler(newValue) {
        if (newValue == null) {
          this.isAllow = 0;
        } else {
          this.isAllow = 1;
        }
      },
      immediate: true,
      deep: true // 默认值是 false，代表是否深度监听
    }
  },
  methods: {
    putImage(item){
      this.$emit("putImage", item);
      console.log(item);
    },
    openImage(item){
      this.$emit("openImage", item);
      console.log(item);
    },
    // 基础数据部分  有快捷查询数据
    openDialog(item) {
      this.$emit("openDialog", item, this.model);
      console.log(item);
    },
    // 获取到焦点的时候获取带出数据的url
    focusInput(item) {
      console.log(item);

      this.quickUrl = item.quickUrl;
      this.$emit("actionValueClick", item.actionValue, this.model);
    },
    // 【远程搜索下拉数据】 dataSelect 下拉快速查询
    async remoteMethod(queryString) {
      console.log(queryString);
      if (queryString != "") {
        this.loading = true;
        setTimeout(() => { //超时延迟下拉快速搜索
        this.getLineChart(queryString);
        }, 5000);
      }
     
    },

    async getLineChart(queryString){ //超时延迟下拉快速搜索
      if (queryString != "") {
        let { data: res } = await this.$http.get(
          "/api/" + this.quickUrl + queryString,
          {
            params: {
              orgId: this.orgData.orgType
            }
          }
        );
        if (res.result) {
          this.loading = false;
          this.selectHeader = res.obj.titleParam;
          this.options = res.obj.items;
        } else {
          this.$message.error(res.msg);
        }
      }
    },

    // findSelect获得焦点的时候，获取数据下拉框的数据 findSelectClick
    findSelectClick(item) {
      let paramsData = this.formParam.params.find(e => {
        // return e.type == "dataSelect" && e.actionValue == "materialId";
        return e.actionValue == item.unActionValue;
      });
      console.log(item);
      console.log(paramsData);
      if (paramsData.actionValue == "materialId") {
        this.materialId = "materialId";
      }
      if (paramsData.lockValue) {
        var lockValue = paramsData.lockValue; // 获取物料ID
      } else if (paramsData.value) {
        var lockValue = paramsData.value;
      }

      this.$nextTick(async () => {
        if (lockValue !== null) {
          this.$emit("actionValueClick", item.actionValue, this.model);
          let { data: res } = await this.$http.get(
            "/api/" + item.actionUrl + lockValue
          );
          // console.log(res);
          if (res.result) {
            this.findSelectHeader = res.obj.titleParam; // 表头数据
            // this.findOptions = res.obj.items;  // 表体数据
            this.formParam.params.forEach((element, eleIndex) => {
              if (element == item) {
                this.formParam.params[eleIndex].selectItems = res.obj.items;
              }
            });
          } else {
            this.$message.error(res.msg);
          }
        } else {
          this.$message.error("请选择" + paramsData.title);
        }
      });
    },
    // findSelect下拉的时候，记录原先选中的数据值
    prepare(callback, item) {
      if (callback) {
        console.log(item);
        this.findPreData = JSON.parse(JSON.stringify(item));
      }
    },

    // getSelect类型
    getSelectClick(item) {
      let paramsData = this.formParam.params.find(e => {
        // return e.type == "dataSelect" && e.actionValue == "materialId";
        return e.type == "dataSelect" && e.actionValue == item.unActionValue;
      });

      console.log(paramsData);
      if (paramsData != undefined) {
        let lockValue = paramsData.lockValue; // 获取物料ID
        this.$nextTick(async () => {
          if (lockValue !== null) {
            this.$emit("actionValueClick", item.actionValue, this.model);
            let { data: res } = await this.$http.get(
              "/api/" + item.actionUrl + lockValue
            );
            // console.log(res);
            if (res.result) {
              this.getSelectHeader = res.obj.titleParam; // 表头数据
              // this.findOptions = res.obj.items;  // 表体数据
              this.formParam.params.forEach((element, eleIndex) => {
                if (element == item) {
                  this.formParam.params[eleIndex].selectItems = res.obj.items;
                }
              });
            } else {
              this.$message.error(res.msg);
            }
          } else {
            this.$message.error("请选择" + paramsData.title);
          }
        });
      } else {
        this.$message.error("异常字段");
      }
    },
    getPrepare(callback, item) {
      if (callback) {
        console.log(item);
        this.getPreData = JSON.parse(JSON.stringify(item));
      }
    },
    // getSeletc的选中事件
    getReturnData(rowdata) {
      console.log(rowdata);
      this.$emit("returnData", JSON.parse(JSON.stringify(rowdata)), 0);
    },
    // 下拉隐藏和显示的时候触发事件
    visibleChange(k) {
      if (!k) {
        this.selectHeader = [];
        this.options = [];
      }
    },
    // 选中建议的值的时候  //下拉返回的
    returnData(rowdata) {
      console.log(rowdata);
      this.$emit("returnData", JSON.parse(JSON.stringify(rowdata)), 0);
    },
    // findSelect类型的返回数据 例如BOM版本
    findReturnData(rowdata) {
      console.log(rowdata);
      console.log(this.materialId);

      if (this.materialId == "materialId") {
        this.$confirm("系统将自动生成新的部件结构数据，是否继续", "⚠警告", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$emit("returnData", JSON.parse(JSON.stringify(rowdata)), 1);
          })
          .catch(() => {
            // 回填原先的数据值
            this.formParam.params.forEach((element, eleIndex) => {
              if (element.paramName == this.findPreData.paramName) {
                this.formParam.params[eleIndex] = JSON.parse(
                  JSON.stringify(this.findPreData)
                );
              }
            });
          });
      } else {
        this.$emit("returnData", JSON.parse(JSON.stringify(rowdata)), 0);
      }
    },

    // 表单预校验
    validateRForm() {
      let flag = null;
      this.$refs.editFormRef.validate(valid => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });
      return flag;
    },

    //  双击打开修改数据
    async rowDblclick(row) {
      let params = {
        openType: row.openType, //用于打开页面
        rowId: row.lockValue,
        name: row.title + "-" + "修改",
        url: row.openUrl
        // key: this.itemPath.key
      };
      console.log(params);
      this.$store.commit("eidtActionPath", JSON.parse(JSON.stringify(params)));
      this.$store.commit("pushTabPathList", this.$store.state.activePath);
    }
  }
};
</script>

<style scoped>
.inputBasicContain {
  width: 100%;
  height: 100%;
}

.selectHeaderClass,
.selectTd {
  min-width: 120px;
  height: 100%;
  flex: 1;
  display: flex;
  align-items: center;
  padding: 0 5px;
  box-sizing: border-box;
  border-right: 1px solid #333;
  flex-shrink: 0;
  /**0 不缩小  1 缩小 */
  flex-grow: 1;
  /**0 不放大  1 放大 */
  overflow: hidden;
  /*溢出隐藏*/
  white-space: nowrap;
  /*溢出不换行*/
  text-overflow: ellipsis;
  /*文字超出宽度则显示ellipsis省略号*/
}

.selectHeaderClass:last-child {
  border: none;
}

.selectTd:last-child {
  border: none;
}

.headerTr {
  width: 100%;
  height: 24px;
  font-size: 13px;
  display: flex;
  background-color: #eeeeee;
  position: sticky;
  top: 0;
  z-index: 99;
}

.selectTr {
  height: 100%;
  display: flex;
}

.optionContain {
  padding: 0 !important;
  font-size: 12px !important;
}

.searchIcon {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translate(0, -50%);
  color: #30a7d6;
  font-weight: 700;
  font-size: 20px;
}
</style>
<style>
.inputBasicTextArea .el-textarea__inner {
  min-height: 80px !important;
  color: #7a7070 !important;
  font-family: "微软雅黑";
}

.inputBasicContain .el-form-item__content {
  width: 180px !important;
}
.textColor .el-input__inner {
  color: blue !important;
}
</style>